//
//  GADService.m
//  AppFrameWork
//
//  Created by Le Anh Tai on 4/26/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "GADService.h"
#import "UIConstants.h"


@implementation GADService

static GADService *_shared;

+(GADService *)shared
{
    if (_shared == nil)
    {
        _shared = [[GADService alloc] init];
    }
    
    return _shared;
}

- (id)init
{
    if (self = [super init])
    {
        if (IS_IPHONE)
        {
            _bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
        }
        else
        {
            _bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeLeaderboard];
        }
    }
    
    return self;
}

-(void)showGADAtBottomWithRootViewController:(UIViewController *)aRootController
{
    unsigned int statusBarHei = [UIApplication sharedApplication].statusBarHidden?0:20;
    [self showGADAt:CGPointMake((aRootController.view.width - _bannerView.width)/2, SCREEN_SIZE.height - statusBarHei - [self heightGAD]) andRootViewController:aRootController];
}

-(void)showGADAtTopWithRootViewController:(UIViewController *)aRootController
{
    [self showGADAt:CGPointMake(0, 0) andRootViewController:aRootController];
}

- (CGFloat)heightGAD
{
    return _bannerView.height;
}

- (void) showGADAt:(CGPoint) aPos andRootViewController:(UIViewController*) aRootController
{
    if (_bannerView)
    {
        // Use predefined GADAdSize constants to define the GADBannerView.
        _bannerView.origin = aPos;
        
        _bannerView.delegate = self;
        
        // Note: Edit SampleConstants.h to provide a definition for kSampleAdUnitID
        // before compiling.
        GADRequest *request = [GADRequest request];
        _bannerView.adUnitID = GAD_ID;
        [_bannerView setRootViewController:aRootController];
        [_bannerView loadRequest:request];
    }
}

- (void)updateBannerPosition:(CGPoint)point
{
    _bannerView.origin = point;
}

#pragma mark GADBannerViewDelegate impl

// We've received an ad successfully.
- (void)adViewDidReceiveAd:(GADBannerView *)adView
{
    if (adView.rootViewController)
    {
        [adView removeFromSuperview];
        [adView.rootViewController.view addSubview:_bannerView];
    }
}

- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
{
    [_bannerView performSelector:@selector(loadRequest:) withObject:[GADRequest request] afterDelay:1];
    NSLog(@"GAD with error: %@", [error localizedFailureReason]);
}
@end
